class BufRecver {
  constructor(lenMax) {
    this.buf = Buffer.alloc(lenMax, 0);
    this.bufLen = 0;

    this.bufLenMax = lenMax;
    this._leading = [0x55];
    this._flagStart = [0xd5, 0x7e];
    this._flagEnd = [0x7d, 0x0a];
    this._trailing = [0x00];
    this._status = 0;
    this.setFunFinish(() => {});
  }
  setFunFinish(fun) {
    this._funFinish = fun;
  }
  recv(data, dataLen) {
    let ret = -1;
    let res;

    for (let i = 0; i < dataLen; i++) {
      res = data[i];

      if (this._status < 0x03) {
        //小于3次前导
        if (res == this._leading[0]) {
          this.bufLen = this._status;
          this.buf[this.bufLen++] = res;
          this._status += 1 << 0;
        } else {
          this._status = 0;
        }
      } else if (this._status < 0x07) {
        //起始0
        if (res == this._leading[0]) {
        } else if (res == this._flagStart[0]) {
          this.buf[this.bufLen++] = res;
          this._status += 1 << 2;
        } else {
          this._status = 0;
        }
      } else if (this._status < 0x0f) {
        //起始1
        if (res == this._flagStart[1]) {
          this.buf[this.bufLen++] = res;
          this._status += 1 << 3;
        } else {
          this._status = 0;
        }
      } else if (this._status < 0x1f) {
        //结束符0
        if (res == this._flagEnd[0]) {
          this.buf[this.bufLen++] = res;
          this._status += 1 << 4;
        } else {
          if (this.bufLen >= this.bufLenMax - 10) {
            this._status = 0; //超出最大长度
            return 9;
          } else {
            this.buf[this.bufLen++] = res; //正在接收数据
            ret = 1;
          }
        }
      } else if (this._status < 0x3f) {
        //结束符1
        if (res == this._flagEnd[1]) {
          this.buf[this.bufLen++] = res;
          this._status += 1 << 5;
        } else if (res == this._flagEnd[0]) {
          this.buf[this.bufLen++] = res;
        } else {
          this.buf[this.bufLen++] = res;
          this._status = 0x0f;
        }
      } else if (this._status < 0xff) {
        //小于3次后继
        if (res == this._trailing[0]) {
          this.buf[this.bufLen++] = res;
          this._status += 1 << 6;

          if (this._status == 0xff) {
            //接收完毕
            this._funFinish(this.buf, this.bufLen); //执行函数
            this._status = 0;
            return 0;
          }
        } else {
          this.buf[this.bufLen++] = res;
          this._status = 0x0f;
        }
      } else {
        this._status = 0;
      }
    }
    return ret;
  }
}

module.exports = BufRecver;
